from collections import Counter

import numpy as np
import random



dataset=np.load(r'/home/b8313/coding/music/melody-generator-gan/src/data/data(11149,20,3).npy',allow_pickle=True)

base_data=np.load(r'/home/b8313/coding/music/melody-generator-gan/src/save_/22_04_03/22_04_03_19_13_11/epoch50_gen_data_2.npy',allow_pickle=True)
def stat_pitch_sum(tuplt_lists, init_list: list = None):
    pitch_list_sum = []
    for i in range(200):
        pitch_list_sum.append(0)
    for tuplt_list in tuplt_lists:
        this_pitch_list = tuplt_list



        # pitch_list_sum = list()

        # init


        for p in this_pitch_list:
            pitch_list_sum[int(p)] += 1

    return pitch_list_sum

def stat_v2_sum(tuplt_list):
    v2_dict= {}
    for tup in tuplt_list:
        for v2 in tup:
            if v2 not in v2_dict.keys():
                v2_dict[v2]=1
            else:
                v2_dict[v2]+=1
    return v2_dict
# r_list=[]
# for times in range(dataset.shape[0]):
#     r_list.extend(dataset[times].T[0])
r_list=dataset[:,:,0]
# r_list=np.reshape(r_list,(1))
# raw_data = raw_data[0]
# r_list = [t[0] for t in raw_data]

sum_list = stat_pitch_sum(r_list)
# sum_list=stat_v2_sum(r_list)
# pass
total_size=sum(sum_list)
print(total_size)

p_array=[]
plist=[]
for i in range(len(sum_list)):
    if sum_list[i] != 0:
        p_array.append(i)
        plist.append(float(sum_list[i])/total_size)

N = base_data.shape[0]*base_data.shape[1]  ##抽样次数
n = len(p_array)

Psample = []
mySample=[]

index = int(random.random() * n)
mw = max(plist)
beta = 0.0

for i in range(N):  ##核心算法
    beta = beta + random.random() * 2.0 * mw
    while beta > plist[index]:
        beta = beta - plist[index]
        index = (index + 1) % n
    Psample.append(plist[index])
    mySample.append(p_array[index])

# cresult = Counter(Psample)
# print('Psample : {}'.format(Psample))
# psam = [cresult[x] for x in plist]
# pe = [x * N for x in plist]

out_data=np.array(mySample).reshape((300,-1))
# np.save(r'data\v230020random2',out_data)
print(out_data)



